package com.xsm.activitygroup;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.xsm.DataBase.ReadMessage;
import com.xsm.DataBase.SaveMessage;
import com.xsm.activitygroup.R;
import com.xsm.adapter.BooksAdapter;
import com.xsm.adapter.MyAdapter;
import com.xsm.adapter.PaiHangAdapter;
import com.xsm.internet.PostMessage;
import com.xsm.object.BookObject;
import com.xsm.object.CTextObject;
import com.xsm.object.ClassifiObject;
import com.xsm.object.PaihangObject;
import com.xsm.object.QuanziObject;
import com.xsm.view.Mydialog;

import android.R.anim;
import android.R.array;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.widget.DrawerLayout;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class activity2 extends Activity{
TextView typeb,placeb,buyb;
Button More;
Context context;
int PLACE=0;
int TYPE=1;
int BUY=2;
private static int  REFRESHING=0;
ListView booksListView;
PullToRefreshListView pullToRefreshListView;
ArrayList<BookObject> books=new ArrayList<BookObject>();
BooksAdapter  adapter;
ProgressBar bar2;
String placeString="All";
String bookType="All";
String textbookcid="All";
private String typeString="";
Button issue;
float touch=0;
float moveY=0;
float downY=0;
Parcelable state;
private long exitTime = 0;
LinearLayout shopLayout;
RelativeLayout loadlayout,errorlayout;
SharedPreferences sharedPreferences;
ArrayList<BookObject> oldArrayList;
int lastid=0;
int firstid=0;
int refresh=0;
LinearLayout pullview;
DrawerLayout dlayout;
TextView loadTextView;
ListView paixingListView;
ArrayList<PaihangObject> pList=new ArrayList<PaihangObject>();
PaiHangAdapter padapter;
int page=0;
private RelativeLayout LoadLayout;
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity2);
	context=this;
	sharedPreferences=context.getSharedPreferences("XSM", 0);
	typeString=sharedPreferences.getString("Type", "");
	placeString=sharedPreferences.getString("school", "All");
	bookType=sharedPreferences.getString("booktype", "All");	
	textbookcid=sharedPreferences.getString("textbookid", "ALL");
	
	loadTextView=(TextView)findViewById(R.id.loadtext);
	loadlayout=(RelativeLayout)findViewById(R.id.loadlayout);
	initView();
	//弹出蒙版提示
	String type=sharedPreferences.getString("ac2", "");	
	String ntextbookav=sharedPreferences.getString("ntextbookav","0");
	String textbookav=sharedPreferences.getString("textbookav", "0");
	if(Integer.parseInt(ntextbookav)>Integer.parseInt(textbookav))
	typeString="";
	if(typeString.equals("")){
		dlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		loadlayout.setVisibility(View.VISIBLE);
		shopLayout.setVisibility(View.GONE);
		More.setEnabled(false);
		new init().execute();
	}else {
		pullToRefreshListView.setVisibility(View.GONE);
		GetNewDate();
        new getPaiHang().execute();
}
	
}

private void GetNewDate(){
	pullview.setVisibility(View.GONE);
	errorlayout.setVisibility(View.GONE);
	loadlayout.setVisibility(View.VISIBLE);
	new GetNewData().execute();
}


public void Chose(View view){
	dlayout.openDrawer(Gravity.LEFT);
}
public void Dclose(View view){
	dlayout.closeDrawers();
}

public void MorePai(View view){
	dlayout.closeDrawers();
	startActivity(new Intent(context,PaiHang.class));
}
private void initView(){
dlayout=(DrawerLayout)findViewById(R.id.drawer_layout);
More=(Button)findViewById(R.id.More);
paixingListView=(ListView)findViewById(R.id.paihanglist);
padapter=new PaiHangAdapter(pList, context);
paixingListView.setAdapter(padapter);
	pullview=(LinearLayout)findViewById(R.id.pullview);
	shopLayout=(LinearLayout)findViewById(R.id.shoplayout);
	loadlayout=(RelativeLayout)findViewById(R.id.loadlayout);
	errorlayout=(RelativeLayout)findViewById(R.id.errorlayout);
	issue=(Button)findViewById(R.id.issue);
	bar2=(ProgressBar)findViewById(R.id.bar2);		
placeb=(TextView)findViewById(R.id.placeb);
typeb=(TextView)findViewById(R.id.typeb);
buyb=(TextView)findViewById(R.id.buyb);
placeb.setText(placeString);
placeb.setOnClickListener(new OnClickListener() {
	public void onClick(View v) {
		Intent intent=new Intent();
		intent.setClass(context, Conditions.class);
		intent.putExtra("type","school");
		startActivityForResult(intent, 3);		
	}
});

buyb.setOnClickListener(new OnClickListener() {
	public void onClick(View v) {
		Intent intent=new Intent();
		intent.setClass(context, Conditions.class);
		intent.putExtra("type","buy");
		startActivityForResult(intent, 4);		
	}
});


if(bookType.equals("All"))
typeb.setText("书籍类型");
else
typeb.setText(bookType);

if(placeString.equals("All")){
	placeb.setText("出售地点");
}else {
	placeb.setText(placeString);
}




typeb.setOnClickListener(new OnClickListener() {
	public void onClick(View arg0) {
typeb.setEnabled(false);		
	new Thread(new TurnThread()).start();
	}
});




pullToRefreshListView=(PullToRefreshListView)findViewById(R.id.booklist2);
booksListView=pullToRefreshListView.getRefreshableView();
adapter=new BooksAdapter(context, books);
booksListView.setAdapter(adapter);	
booksListView.setOnScrollListener(mScrollListener);
booksListView.setOnTouchListener(mTouchListener);
state=booksListView.onSaveInstanceState();  

pullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
				DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
		bar2.setVisibility(View.VISIBLE);
		  if(touch>=0)
           refresh=1;
	         else 
	       refresh=0; 	 
		  if(REFRESHING==0)
				new GetNewData().execute(); 	 
	}
});

booksListView.setOnItemClickListener(new OnItemClickListener() {
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
  Intent intent=new Intent();
 intent.putExtra("ms",books.get(arg2-1));
 intent.putExtra("index",arg2-1);
 intent.putExtra("type", "sell");
 intent.setClass(context, BookMessage.class);
startActivityForResult(intent,2);
	}
});
}

public void Issue(View view){
	Intent intent=new Intent();
	intent.setClass(context,SearchView.class);
    startActivity(intent);
}


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK){
switch (requestCode) {
case 1:
if(resultCode==RESULT_OK){
String textid=data.getExtras().getString("textid");
String textString=data.getExtras().getString("textString");
textbookcid=textid;	
String name=textString.substring(textString.indexOf("-")+1,textString.length());
typeb.setText(name);	
bookType=name;
if(textid.equals("-1")){
textbookcid="All";
bookType="书籍类型";
typeb.setText(bookType);
}
sharedPreferences.edit().putString("booktype",bookType).commit();
sharedPreferences.edit().putString("textbookid",textbookcid).commit();

page=0;
books.clear();
refresh=1;
bar2.setVisibility(View.VISIBLE);
new GetNewData().execute();
}
break;
case 2:
books.remove(data.getExtras().getInt("index"));	
break;
case 3:
String result=data.getExtras().getString("result");
if(result.equals("全部")){
	placeb.setText("出售地点");	
	placeString="All";
}else {
	placeString=result;
	placeb.setText(placeString);	
}
sharedPreferences.edit().putString("school",placeString).commit();

page=0;
books.clear();
refresh=1;
bar2.setVisibility(View.VISIBLE);
new GetNewData().execute();
break;

case 4:

break;

default:
	break;
}
}
}

public OnTouchListener mTouchListener=new OnTouchListener() {
	public boolean onTouch(View v, MotionEvent event) {
	switch (event.getAction()) {
	case MotionEvent.ACTION_DOWN:
		downY=event.getY();
		break;
	case MotionEvent.ACTION_MOVE:
	    moveY=event.getY();
		break;
	case MotionEvent.ACTION_UP:
		touch=moveY-downY;
		break;	
	default:
		break;
	}return false;
	}
};


public OnScrollListener mScrollListener = new OnScrollListener() {  
    public void onScrollStateChanged(AbsListView view, int scrollState) {  
        state = booksListView.onSaveInstanceState();  
        switch (scrollState) {  
        case OnScrollListener.SCROLL_STATE_FLING:  
            break;  
        case OnScrollListener.SCROLL_STATE_IDLE:  
            break;  
        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:  
            break;  
        default:  
            break;  
        }  
        adapter.notifyDataSetChanged();  
    }

    
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
	} 
    };
    
    
public void onScroll(AbsListView view, int firstVisibleItem,  
            int visibleItemCount, int totalItemCount) {  
};  


private String  addnewData(){
   if(refresh==1)
   page=0;
   else {
   page=books.size();
   }
   
	String userid=sharedPreferences.getString("User", "");
	List params=new ArrayList();
	params.add(new BasicNameValuePair("ASK","GetGoodsSimpleMessage"));
	params.add(new BasicNameValuePair("school",placeString));
	params.add(new BasicNameValuePair("booktype",textbookcid));
	params.add(new BasicNameValuePair("page",page+""));

	PostMessage postMessage=new PostMessage(params);
	String result=postMessage.getResult();
	JSONArray array = null;
	try {
		 array=new JSONArray(result);
		 if(array.length()>0){
			 if(refresh==1)
			 books.clear(); 
		 }
		JSONObject jobject=new JSONObject();
		for(int i=0;i<array.length();i++){
			jobject=array.optJSONObject(i);
			String bookname=jobject.getString("bookname");
			String time=jobject.getString("time");
			String price=jobject.getString("price");
			String bookType=jobject.getString("booktype");	
			String school=jobject.getString("school");
			String press=jobject.getString("press");
			String goodsid=jobject.getString("goodsid");
			String author=jobject.getString("author");
			String realprice=jobject.getString("realprice");
			String gparentid=jobject.getString("gparentid");
			String issueuserid=jobject.getString("userid");
			
			BookObject object=new BookObject();
			object.setBookName(bookname);
			object.setTime(time.substring(0,10));
			object.setPrice(price);
			object.setBookType(bookType);
			object.setPlace(school);
			object.setPress(press);
			object.setGoodsid(goodsid);
			object.setAuthor(author);
			object.setGparentid(gparentid);
			object.setRealprice(realprice);
			object.setUserid(issueuserid);
			books.add(object);	
		}
	} catch (Exception e) {
		Log.d("my", e+"");
	}
	new SaveMessage(context).SaveBooks(books);
	return result;
}



public class GetNewData extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {
	REFRESHING=1;
	String result;
	result=addnewData();
		return result;
	}
	protected void onPostExecute(String result) {
		REFRESHING=0;
		loadlayout.setVisibility(View.GONE);
		pullToRefreshListView.setVisibility(View.VISIBLE);
		if(books.size()>0){
		pullview.setVisibility(View.GONE);
		}
		else{
		pullview.setVisibility(View.VISIBLE);
		}
		if(books.size()<3){
			pullToRefreshListView.setMode(Mode.PULL_DOWN_TO_REFRESH);
		}else {
			pullToRefreshListView.setMode(Mode.BOTH);
		}
		pullToRefreshListView.onRefreshComplete();
        adapter.notifyDataSetChanged();
        bar2.setVisibility(View.GONE);
        if(result.equals("-1")){
       Toast.makeText(context, "连接服务器失败", Toast.LENGTH_LONG).show();
         }
		super.onPostExecute(result);
	}
}



public class init extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {
		 new SaveMessage(context).initType();	
	      addnewData();
		 String reString="";
		 SharedPreferences sharedPreferences=context.getSharedPreferences("XSM", 0);
		String typeString=sharedPreferences.getString("Type", "");
		if(typeString.equals(""))
			reString="no";
		else {
			reString="yes";
		}
		return reString;
	}
	protected void onPostExecute(String result) {
		if(result.equals("yes")){
	    pullview.setVisibility(View.GONE);
		loadlayout.setVisibility(View.GONE);
		shopLayout.setVisibility(View.VISIBLE);
		errorlayout.setVisibility(View.GONE);
		initView();	
		dlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        adapter.notifyDataSetChanged();
        More.setEnabled(true);
        }else {
        	loadlayout.setVisibility(View.GONE);
        	errorlayout.setVisibility(View.VISIBLE);
		}
		super.onPostExecute(result);
	}
}

public void Update(View view){
	errorlayout.setVisibility(View.GONE);
	loadlayout.setVisibility(View.VISIBLE);
	shopLayout.setVisibility(View.GONE);
	new init().execute();
}
protected void onResume() {
	if(booksListView!=null){
	booksListView.setAdapter(adapter);
	booksListView.onRestoreInstanceState(state);
	}
	if(paixingListView!=null){
		paixingListView.setAdapter(padapter);
	}
	
	MobclickAgent.onResume(this);
	super.onResume();
	}

    protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
	}
    
    


public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
        if((System.currentTimeMillis()-exitTime) > 2000){  
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_LONG).show();                                
            exitTime = System.currentTimeMillis();   
        } else {
         int pid=android.os.Process.myPid();
         android.os.Process.killProcess(pid);
        }
        return true;   
    }
    return super.onKeyDown(keyCode, event);
}

public class getPaiHang extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {
		List param=new ArrayList();
		param.add(new BasicNameValuePair("ASK","GetPaihang"));
		param.add(new BasicNameValuePair("page","0"));
		PostMessage postMessage=new PostMessage(param);
		String result=postMessage.getResult();
		try {
			JSONArray array=new JSONArray(result);
			if(array.length()>0){
			pList.clear();				
			}	
			for(int i=0;i<array.length();i++){
				PaihangObject object=new PaihangObject();
				JSONObject jObject=array.optJSONObject(i);
				object.fenshu=jObject.getString("fenshu");
				object.issuecount=jObject.getString("issuecount");
				object.outcount=jObject.getString("outcount");
				object.user=jObject.getString("username");
			    pList.add(object);	
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return result;
	}
	protected void onPostExecute(String result) {
		paixingListView.setVisibility(View.VISIBLE);
		if(result.equals("-1")){
			loadTextView.setText("无法获取数据,点击刷新");
			loadTextView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
			loadTextView.setText("正在加载...");		
			new getPaiHang().execute();
				}
			});
		}else {
			if(pList.size()>0){
			loadTextView.setVisibility(View.GONE);
			}
			else {
			loadTextView.setText("暂无最新排行");
		}
		}
		padapter.notifyDataSetChanged();
		super.onPostExecute(result);
	}
}

//加载分类线程
private Ac2Handler handler=new Ac2Handler();
private Intent intent=null;
private class TurnThread implements Runnable{
	public void run() {
		ArrayList<CTextObject> arrayListA=new ReadMessage(context).getTextObject(1);
		CTextObject arrObject=new CTextObject();
		arrObject.setTextid("-1");
		arrObject.setName("全部");
		arrayListA.add(arrObject);
		ArrayList<CTextObject> arrayListB=new ReadMessage(context).getTextObject(2);
		ArrayList<CTextObject> arrayListC=new ReadMessage(context).getTextObject(3);
		intent=new Intent();
	    intent.putExtra("arrayListA", arrayListA);
		intent.putExtra("arrayListB", arrayListB);
	    intent.putExtra("arrayListC", arrayListC);
		intent.setClass(context, Classification.class);
		Message msg=handler.obtainMessage();
		msg.what=1;
		handler.sendMessage(msg);
	}
	
}

class Ac2Handler extends Handler{
	public void handleMessage(Message msg) {
	if(msg.what==1){
		startActivityForResult(intent,1);	
		typeb.setEnabled(true);
	}
	}
}

}
